package ext.tianma.part.finishedProduct.processors;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import wt.csm.navigation.ClassificationNode;
import wt.csm.navigation.litenavigation.ClassificationNodeDefaultView;
import wt.csm.navigation.service.ClassificationObjectsFactory;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.log4j.LogR;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.part.WTPart;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.workflow.definer.WfProcessTemplate;
import wt.workflow.engine.ProcessData;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfEngineServerHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.workflow.WorkflowUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.part.finishedProduct.util.CSMUtil;
import ext.tianma.part.finishedProduct.util.LoadAttrsConfig;
import ext.tianma.util.GetSuperior;
import ext.tianma.workflow.SubmitBomReview;

public class ReleaseFinishedGoodProcessors extends DefaultObjectFormProcessor {
	private static Logger log = LogR.getLogger(ReleaseFinishedGoodProcessors.class.getName());
	private static String processorName = "成品编码申请流程";
	
	@Override
	public FormResult doOperation(NmCommandBean arg0, List<ObjectBean> arg1) throws WTException {
		log.debug("ReleaseFinishedGoodProcessors==>>Start");
		FormResult formresult = new FormResult();
		formresult.setStatus(FormProcessingStatus.SUCCESS);
		NmOid nmoid = arg0.getActionOid();
		WTPart currentPart = (WTPart) nmoid.getRefObject();
		if( currentPart != null ){
			boolean isHasSameSubmit = false;
			QueryResult qr = WfEngineHelper.service.getAssociatedProcesses(currentPart, WfState.OPEN_RUNNING, null);
			WfProcess process = null;
			while (qr.hasMoreElements()) {
				process = (WfProcess) qr.nextElement();
				if (process.getTemplate().getName().equals(processorName)) {
					isHasSameSubmit = true;
				}
			}
			// 测试角色   BOMAssessor.value=BOM审核者    NPIEngineer.value=NPI工程师
			// ODEngineer.value=OD工程师  MEEngineer.value=ME工程师   EEEngineer.value=EE工程师
			
			if(!isHasSameSubmit){
				//升级小版本
				boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
				try{
					//获取分类
					String classifyOid = arg0.getRequest().getParameter("part_classify_hidden");
					ReferenceFactory rf = new ReferenceFactory();
					ClassificationNode node = (ClassificationNode) rf.getReference(classifyOid).getObject();
					//获取节点下所有属性<内部名称，显示名称>
				    Map<String, String> classNodeAllIBAs = CSMUtil.getClassNodeAllIBAs(node);
				    log.debug("classNodeAllIBAs==>>"+classNodeAllIBAs);
				    //获取页面所有属性
				    HashMap<String, List<String>> allPageAttrs = EditFinishedGoodAttrsProcessors.
				    		getAllPageAttrs(currentPart,arg0);
				    if(!allPageAttrs.containsKey("finishedGoodDimension")){
				    	throw new WTException("请联系管理员，配置'产品维度'属性!");
				    }
				    log.debug("allPageAttrs==>>"+allPageAttrs);
				    //获取分类属性
				    HashMap<String, String> classAttrsMap = EditFinishedGoodAttrsProcessors.
				    		getClassAttrsMap(allPageAttrs,classNodeAllIBAs);
				    log.debug("classAttrsMap==>>"+classAttrsMap);
				    //校验分类属性
				    EditFinishedGoodAttrsProcessors.validationClassAttrs(currentPart,classAttrsMap,node);
				    
					currentPart = (WTPart) GenericUtil.checkout(currentPart, "提交"+processorName+"检出");
					currentPart = (WTPart) GenericUtil.checkin(currentPart, "提交"+processorName+"检入");
					//清除分类
					CSMUtil.clearPartClassficationNode(currentPart);
					//设置分类
					CSMUtil.setPartClassficationNode(currentPart, node);
					//设置属性
					EditFinishedGoodAttrsProcessors.setPartAttrs(currentPart,allPageAttrs,node,classNodeAllIBAs);
					
					//启动流程
					WfProcessTemplate wfprocessTemplate = SubmitBomReview.getWfProcessTemplateByName(processorName);//获取流程模板
					WTPrincipal wtprincipal = SessionHelper.manager.getPrincipal();
					String processName = "成品编码申请流程_"+currentPart.getNumber();
					WTPrincipalReference wtprincipalreference = WTPrincipalReference.newWTPrincipalReference(wtprincipal);
				
					WfProcess wfprocess = WfEngineHelper.service.createProcess(wfprocessTemplate, currentPart.getLifeCycleTemplate(),currentPart.getContainerReference());
					WfEngineServerHelper.service.setPrimaryBusinessObject(wfprocess,currentPart);
					wfprocess.setName(processName);
		    		ProcessData processdata = wfprocess.getContext();
		    		wfprocess.setCreator(wtprincipalreference);
		    		
		    		wfprocess = (WfProcess)PersistenceHelper.manager.save(wfprocess);	
		    		wfprocess.start(processdata, true, currentPart.getContainerReference());
		    		
		    		//为流程节点设置参与者
		    		String finishedGoodDimension = allPageAttrs.get("finishedGoodDimension").get(0);
		    		ClassificationNodeDefaultView cndv=ClassificationObjectsFactory.newClassificationNodeDefaultView(node);
		        	String fullPath = CSMUtil.getClassificationFullPath(cndv);
		    		List<String> roleNameList = LoadAttrsConfig.getMaintainRolesName(fullPath,finishedGoodDimension);
		    		for(String roleName : roleNameList){
		    			if("PM".equals(roleName)){
		    				continue;
		    			}
		    			String userCn = arg0.getRequest().getParameter(roleName);
		    			log.debug("userCn==>>"+userCn);
		    			if(null != userCn && userCn.length() > 0){
		    			    String userUid = getUid(userCn);
		    				WorkflowUtil.addPrincipalToProcessRole(wfprocess,roleName, GetSuperior.getUserFromName(userUid));
		    			}
		    		}
		    		
		    		//String user_bom = arg0.getRequest().getParameter("BOMSigner");
		    		//String userBomUid = getUid(user_bom);
	    			//WorkflowUtil.addPrincipalToProcessRole(wfprocess,"BOMSigner", GetSuperior.getUserFromName(userBomUid));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					throw new WTException(e.getLocalizedMessage());
				}finally {
					SessionServerHelper.manager.setAccessEnforced(flag);
				}			
				
				FeedbackMessage feedbackmessage = new FeedbackMessage(
						FeedbackType.SUCCESS, null, "启动"+processorName, null, new String[] {});
				formresult.addFeedbackMessage(feedbackmessage);
				return formresult;
			}
			
			FeedbackMessage feedbackmessage = new FeedbackMessage(
					FeedbackType.FAILURE, null, "启动"+processorName, null, "该流程已存在,请查看!");
			formresult.addFeedbackMessage(feedbackmessage);
		}
		return formresult;
	}
	
	private static String getUid(String uidInfo) {
		String uid = "";
		if(null != uidInfo && uidInfo.length() > 0) {
			uid = uidInfo.split(",")[0].split("=")[1];
		}
		return uid;
	}
}
